package com.teamall.core.common;

import com.teamall.core.spring.context.CustomPropertyConfigurer;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.util.MailInfo;
import com.teamall.web.tssy.db.po.TsSyUserPO;
import com.teamall.web.tssy.service.ITsSyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public abstract class BaseController {
    protected static String operSuccess = "操作成功";
    protected static String operFail = "操作失败";
    public final static String LOGIN_SESSION_KEY = "SYSUSER_LOGIN_SESSIONID";
    public final static String SYSTEM_ADMIN = "Administrator";
    public final static String PERMISSION_KEY = "SESSION_PERMISSION";
    public static String userId = "";//登录人ID
    public static TsSyUserPO loginUser = new TsSyUserPO();//登录人

    public static MailInfo mailInfo = new MailInfo();
    @Autowired
    private ITsSyUserService tsSyUserService;

    /**
     * 初始化获取登录人信息
     *
     * @param model
     */
    @ModelAttribute
    public void initBaseData(Model model) {
        loginUser = (TsSyUserPO) getSession().getAttribute(BaseController.LOGIN_SESSION_KEY);
        if (loginUser != null) {
            userId = loginUser.getId();
        }
        try {
            List<TsSyUserPO> baseUserList = tsSyUserService.selectByArg(new TsSyUserPO());
            model.addAttribute("baseUserList", baseUserList);
        } catch (BaseAppException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected ModelAndView ajaxDoneSuccess(String message) {
        return ajaxDone(200, message, "");
    }

    protected ModelAndView ajaxDoneSuccess(String message, String forwardUrl) {
        return ajaxDone(200, message, forwardUrl);
    }


    /**
     * 将dwz分页参数转成Page对象
     *
     * @param message
     * @param result
     * @return
     */
    protected Page dwzToPage(DwzPage dwzPage) {
        Page page = new Page();

        if (dwzPage != null && dwzPage.getPageSize() > 0) {
            page.setLimit(dwzPage.getPageSize());
        }
        if (dwzPage != null && dwzPage.getPageCurrent() > 0) {
            page.setPage(dwzPage.getPageCurrent());
        }

        page.setStart((page.getPage() - 1) * page.getLimit());//起始记录下标

        return page;
    }

    /**
     * 将dwz分页参数转成Page对象
     * @return
     */
    protected String getConditions(Object obj) {
        if (obj == null) {
            return "";
        }
        String retStr = "";
        ArrayList list = new ArrayList();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int j = 0; j < fields.length; j++) {
            Field field = fields[j];
            try {
                String name = field.getName();
                String type = field.getType().getName();
                field.setAccessible(true);
                if (field.get(obj) != null && !"".equals(field.get(obj))) {
                    retStr += "{\"paramName\":\"" + name + "\",\"operation\":\"Like\",\"paramValue\":[\"" + field.get(obj) + "\"]},";
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if ("".equals(retStr)) {
            return "";
        } else {
            retStr = "[" + retStr.substring(0, retStr.length() - 1) + "]";
            return retStr;
        }

    }

    public static void main(String[] arsg) {

    }

    /**
     * 不含返回处理结果信息
     *
     * @param message
     * @param result
     * @return
     */
    protected ModelAndView ajaxDone(int statusCode, String message, String forwardUrl) {
        ModelAndView mv = new JModelAndView("common/ajaxDone");
        mv.addObject("statusCode", statusCode);
        mv.addObject("message", message);
        mv.addObject("forwardUrl", forwardUrl);
        HttpServletRequest httprequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        mv.addObject("httprequest", httprequest);
        return mv;
    }

    /**
     * 含返回处理结果信息
     *
     * @param message
     * @param result
     * @return
     */
    protected ModelAndView ajaxDone(int statusCode, String message, String forwardUrl, Object result) {
        ModelAndView mav = new JModelAndView("common/ajaxDone");
        mav.addObject("statusCode", statusCode);
        mav.addObject("message", message);
        mav.addObject("forwardUrl", forwardUrl);
        mav.addObject("result", result);
        return mav;
    }

    /**
     * 含返回处理结果信息
     *
     * @param message
     * @param result
     * @return
     */
    protected ModelAndView ajaxDoneSuccess(String message, Object result) {
        return ajaxDone(200, message, "", result);
    }

    protected ModelAndView ajaxDoneError(String message) {
        return ajaxDone(300, message, "");
    }

    protected String getMessage(String code) {
        return this.getMessage(code, new Object[]{});
    }

    protected String getMessage(String code, Object arg0) {
        return getMessage(code, new Object[]{arg0});
    }

    protected String getMessage(String code, Object arg0, Object arg1) {
        return getMessage(code, new Object[]{arg0, arg1});
    }

    protected String getMessage(String code, Object arg0, Object arg1,
                                Object arg2) {
        return getMessage(code, new Object[]{arg0, arg1, arg2});
    }

    protected String getMessage(String code, Object arg0, Object arg1,
                                Object arg2, Object arg3) {
        return getMessage(code, new Object[]{arg0, arg1, arg2, arg3});
    }

    /**
     * 获取网站上下文路径（Context path）
     *
     * @param request Servlet请求对象
     * @return 网站上下文路径
     */
    public String getWebPath(HttpServletRequest request) {
        return (request.getContextPath().equals("/") ? "" : request.getContextPath());
    }
//	/**
//	 * 获取当前登录者信息
//	 * @return
//	 */
//	public TEmployeePO getCurUser(){
//		return (TEmployeePO)getSession().getAttribute(LOGIN_SESSION_KEY);
//	}

    /**
     * 获取当前session
     *
     * @return
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public String getPlatFormAccount() {
        return (String) CustomPropertyConfigurer.getContextProperty("platform.accountID");
    }

    /**
     * 获取远程访问的IP、端口、工程名称
     *
     * @param request
     * @return
     */
    public String getUrl(HttpServletRequest request) {
        String ip = request.getRemoteHost();
        String projectName = request.getContextPath();
        int port = request.getServerPort();
        return "http://" + ip + ":" + port + projectName;
    }
}
